package com.mhsoft.fenak.utils;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;

public class MyHttpPostAsyncTask extends AsyncTask<Object, Void, Integer>{

	private UpdateUI_Interface caller;
	private String[] result;
	private ArrayList<NameValuePair> nameValuePairs;
	private String url;
	private ProgressDialog progressDialog;
	
	private Activity activity;
	
	public MyHttpPostAsyncTask(Activity a){
		
		this.activity = a;
	}

	@Override
	protected Integer doInBackground(Object... params) {
		
		Integer statusCode = new Integer(0);
		
		// result[0] = response state.
		// result[1] = response string.
		// result[2] = where to modify.
		result = new String[3];
		
		
		caller = (UpdateUI_Interface) activity;
		url = (String) params[0];
		result[2] = (String) params[1];
		nameValuePairs = (ArrayList<NameValuePair>) params[2];
		
		progressDialog = (ProgressDialog) params[3];
		
		HttpClient httpClient = new DefaultHttpClient();
		
		HttpPost httppost = new HttpPost(url);
		
		try {
			
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			
			// Execute HTTP Post Request
		    HttpResponse response = httpClient.execute(httppost);
		    
		    statusCode = response.getStatusLine().getStatusCode();
		    
		    result[1] = ConnectionManager.getResponseString(response.getEntity().getContent());
		    
		} catch (ClientProtocolException e) {

			Log.v("ERROR In MyHttpPostAsyncTask", "ClientProtocolException");
			
			e.printStackTrace();
			
		} catch (IOException e) {

			Log.v("ERROR In MyHttpPostAsyncTask", "Connection problem");
			
			e.printStackTrace();
		}
		
		isCancelled();
		
		return statusCode;
	}
	
	@Override
	protected void onPostExecute(Integer result) {
		
		this.result[0] = result.intValue()+"";
		
		caller.updateUI(this.result);
		
		progressDialog.dismiss();
		
		super.onPostExecute(result);
	}

	@Override
	protected void onCancelled() {
		super.onCancelled();
		
		progressDialog.dismiss();
	}
}
